import React, { Component, Fragment } from "react";
import Form from "./Form";
import List from "./List";

class App extends Component {
  // 要在app里面定义list
  state = {
    list: [
      {
        id: 1,
        name: "张三",
      },
      {
        id: 2,
        name: "李四",
      },
    ],
  };

  // 接收子组件传入的内容
  getData = (msg) => {
    // console.log(msg);
    // 添加进list
    this.setState((prevState) => {
      return {
        list: [
          ...prevState.list,
          {
            id: new Date().getTime(),
            name: msg,
          },
        ],
      };
    });
  };

  // 删除的事件
  removeItem = (id) => () => {
    // console.log(id);
    // list里面删除对应的项
    this.setState((prevState) => {
      return {
        list: prevState.list.filter((item) => item.id !== id),
      };
    });
  };

  render() {
    const { list } = this.state;
    return (
      <Fragment>
        {/* 通过自定义事件，可以让子组件触发父组件事件并传参 */}
        <Form onGetData={this.getData} />
        {/* 通过自定义属性进行父传子 */}
        <List list={list} onRemove={this.removeItem} />
      </Fragment>
    );
  }
}

export default App;
